package com.xzy.custom;

import com.xzy.entities.SysRole;
import com.xzy.entities.SysUser;
import com.xzy.security.UserShow;
import com.xzy.service.SysRoleService;
import com.xzy.service.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * TODO70
 *
 * @author Administrator
 * ClassName: MyUserDetailsService
 * date: 2021/11/12 11:08
 */
@Service
public class MyUserDetailsService implements UserDetailsService {

    @Autowired
    private SysUserService userService;
    @Autowired
    private SysRoleService roleService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser user= userService.findByUserName(username);
        if(user==null) {
            throw new UsernameNotFoundException(username);
        }
        List<GrantedAuthority> authorities=new ArrayList<>();
        List<SysRole> roles = roleService.findByUserId(user.getId());
        for (SysRole role : roles) {
            authorities.add(new SimpleGrantedAuthority(role.getRoleCode()));
        }
        return new UserShow(user.getUsername(), user.getPassword(),user.getName(), authorities);
    }
}
